package com.junxonline.plat.service.floorplan.impl;

import com.junxonline.common.util.CommonUtils;
import com.junxonline.common.util.FileUtils;
import com.junxonline.plat.dao.model.House;
import com.junxonline.plat.dao.model.HouseFloorPlan;
import com.junxonline.plat.dao.model.Household;
import com.junxonline.plat.dao.model.Position;
import com.junxonline.plat.dao.repository.FloorPlanRepository;

import com.junxonline.plat.dao.vo.*;
import com.junxonline.plat.exception.PlatBizException;
import com.junxonline.plat.service.floorplan.FloorPlanService;
import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.persistence.criteria.*;
import javax.servlet.http.HttpServletRequest;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;

@Service
@Transactional
public class FloorPlanServiceImpl implements FloorPlanService {

    @Value("${wms.floorplan.save.path}")
    private String savePath;

    @Autowired
    private FloorPlanRepository floorPlanRepository;

    /**
     * 获取户型数据
     *
     * @param vo
     * @return
     */
    @Override
    public FloorPlanVO getFloorPlan(QueryFloorPlanVO vo) {

        HouseFloorPlan tempFloorPlan = floorPlanRepository.findByHouseFloorPlanId(vo.getHouseFloorPlanId());

        FloorPlanVO floorPlanVO = new FloorPlanVO();

        floorPlanVO.setHouseFloorPlanId(tempFloorPlan.getHouseFloorPlanId());
        floorPlanVO.setHouseFloorPlanName(tempFloorPlan.getHouseFloorPlanName());
        floorPlanVO.setHouseFloorPlanNo(tempFloorPlan.getHouseFloorPlanNo());

        String realPath = tempFloorPlan.getHouseFloorPlanFilePath();

        // 读取文件
        String imgBase64 = FileUtils.readFile(realPath);

        floorPlanVO.setHouseFloorPlanFileBase64(imgBase64);

        return floorPlanVO;
    }

    /**
     * 筛选查询户型
     *
     * @param pageVO
     * @param vo
     * @return
     */
    @Override
    public PageVO queryFloorPlan(PageVO pageVO, QueryFloorPlanVO vo) {
        PageRequest pageRequest = PageRequest.of(pageVO.getPage() - 1, pageVO.getLimit(), new Sort(Sort.Direction.ASC, "houseFloorPlanId"));

        Page<HouseFloorPlan> page = floorPlanRepository.findAll(new Specification<HouseFloorPlan>() {
            @Override
            public Predicate toPredicate(Root<HouseFloorPlan> root, CriteriaQuery<?> criteriaQuery, CriteriaBuilder criteriaBuilder) {

                List<Predicate> params = new ArrayList<>();
                String houseFloorPlanNo = vo.getHouseFloorPlanNo();
                String houseFloorPlanName = vo.getHouseFloorPlanName();

                if (CommonUtils.isNotEmpty(houseFloorPlanNo)) {
                    params.add(criteriaBuilder.like(root.get("houseFloorPlanNo"), "%" + houseFloorPlanNo + "%"));
                }

                if (CommonUtils.isNotEmpty(houseFloorPlanName)) {
                    params.add(criteriaBuilder.like(root.get("houseFloorPlanName"), "%" + houseFloorPlanName + "%"));
                }

                return criteriaBuilder.and(params.toArray(new Predicate[params.size()]));
            }
        }, pageRequest);

        List<FloorPlanVO> floorPlanVOs = new ArrayList<>();
        List<HouseFloorPlan> floorPlans = page.getContent();

        for (HouseFloorPlan ouseFloorPlan : floorPlans) {

            FloorPlanVO floorPlanVO = new FloorPlanVO();

            floorPlanVO.setHouseFloorPlanId(ouseFloorPlan.getHouseFloorPlanId());
            floorPlanVO.setHouseFloorPlanName(ouseFloorPlan.getHouseFloorPlanName());
            floorPlanVO.setHouseFloorPlanNo(ouseFloorPlan.getHouseFloorPlanNo());

            floorPlanVO.setHouseFloorPlanFilePath(ouseFloorPlan.getHouseFloorPlanFilePath());

            floorPlanVOs.add(floorPlanVO);

        }

        pageVO.setTotal(page.getTotalElements());
        pageVO.setData(floorPlanVOs);

        return pageVO;
    }

    /**
     * 添加户型
     *
     * @param vo
     * @return
     */
    @Override
    public boolean addFloorPlan(FloorPlanVO vo) {

        StringBuilder floorPlanNO = new StringBuilder();
        floorPlanNO.append("HIDNO");

        HouseFloorPlan tempFloorPlan = floorPlanRepository.findByFloorPlanIdLast();
        if (CommonUtils.isEmpty(tempFloorPlan)) {
            floorPlanNO.append("000001");
        }
        else {
            DecimalFormat decimalFormat = new DecimalFormat("000000");
            String currentNO = tempFloorPlan.getHouseFloorPlanId().toString();
            String nextNO = decimalFormat.format(Integer.parseInt(currentNO) + 1);
            floorPlanNO.append(nextNO);
        }

        HouseFloorPlan floorPlan = new HouseFloorPlan();

        floorPlan.setHouseFloorPlanName(vo.getHouseFloorPlanName());
        floorPlan.setHouseFloorPlanNo(floorPlanNO.toString());

        String imgPath = savePath;

        // 将图片保存到服务器上
        String realPath = FileUtils.saveFile(vo.getHouseFloorPlanFile(), imgPath);

        // 将图片路径存入数据库
        floorPlan.setHouseFloorPlanFilePath(realPath);

        floorPlanRepository.save(floorPlan);

        return true;
    }

    /**
     * 修改户型
     *
     * @param vo
     * @return
     */
    @Override
    public boolean editFloorPlan(FloorPlanVO vo) {

        HouseFloorPlan floorPlan = floorPlanRepository.findByHouseFloorPlanId(vo.getHouseFloorPlanId());

        floorPlan.setHouseFloorPlanName(vo.getHouseFloorPlanName());

        String imgPath = savePath;

        // 将图片保存到服务器上
        String realPath = FileUtils.saveFile(vo.getHouseFloorPlanFile(), imgPath);

        // 将图片路径存入数据库
        floorPlan.setHouseFloorPlanFilePath(realPath);

        floorPlanRepository.save(floorPlan);

        return true;
    }

    /**
     * 删除户型
     *
     * @param floorPlanIds
     * @return
     */
    @Override
    public boolean delFloorPlan(Long[] floorPlanIds) {

        List<HouseFloorPlan> floorPlans = floorPlanRepository.findByHouseFloorPlanIdIn(floorPlanIds);

        for (HouseFloorPlan floorPlan : floorPlans) {

            // 先查看该户型是否有房产在使用
            List<House> houses = floorPlan.getHouses();
            if (CommonUtils.isNotEmpty(houses)) {
                throw PlatBizException.HOUSE_HAVE_FLOOR_PLAN_DELETE_ERROR;
            }

            floorPlanRepository.delete(floorPlan);

        }

        return true;
    }
}
